<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单创建问题诊断</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .diagnostic-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .warning { color: orange; }
        .diagnostic-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .diagnostic-btn:hover { background: #0056b3; }
        .json-display { background: #f8f9fa; padding: 10px; border-radius: 4px; white-space: pre-wrap; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto; }
    </style>
</head>
<body>
    <h1>订单创建问题诊断工具</h1>
    
    <div class="diagnostic-section">
        <h3>1. 检查当前用户状态</h3>
        <button class="diagnostic-btn" onclick="checkUserStatus()">检查用户状态</button>
        <div id="userStatus"></div>
    </div>
    
    <div class="diagnostic-section">
        <h3>2. 检查所有用户订单</h3>
        <button class="diagnostic-btn" onclick="checkAllOrders()">检查所有订单</button>
        <div id="allOrders"></div>
    </div>
    
    <div class="diagnostic-section">
        <h3>3. 模拟创建订单</h3>
        <button class="diagnostic-btn" onclick="simulateCreateOrder()">模拟创建订单</button>
        <div id="createOrderResult"></div>
    </div>
    
    <div class="diagnostic-section">
        <h3>4. 检查订单文件</h3>
        <button class="diagnostic-btn" onclick="checkOrderFile()">检查订单文件</button>
        <div id="orderFileResult"></div>
    </div>
    
    <div class="diagnostic-section">
        <h3>5. 调试信息</h3>
        <div id="debugInfo"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const debugDiv = document.getElementById('debugInfo');
            const timestamp = new Date().toLocaleTimeString();
            debugDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            debugDiv.scrollTop = debugDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'warning');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        // 检查用户状态
        function checkUserStatus() {
            const statusDiv = document.getElementById('userStatus');
            try {
                const authToken = localStorage.getItem('authToken');
                const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
                const userData = JSON.parse(localStorage.getItem('userData') || '{}');
                const isAuthenticated = window.authManager ? window.authManager.isAuthenticated() : false;
                const apiUsername = window.api ? window.api.getUsername() : '';
                
                statusDiv.innerHTML = `
                    <div class="info">
                        <strong>认证Token:</strong> ${authToken || '无'}<br>
                        <strong>当前用户 (currentUser):</strong> ${JSON.stringify(currentUser, null, 2)}<br>
                        <strong>用户数据 (userData):</strong> ${JSON.stringify(userData, null, 2)}<br>
                        <strong>认证状态:</strong> ${isAuthenticated ? '已认证' : '未认证'}<br>
                        <strong>API用户名:</strong> ${apiUsername || '无'}<br>
                        <strong>用户名一致性:</strong> ${currentUser.username === userData.username ? '一致' : '不一致'}
                    </div>
                `;
                
                console.log('用户状态检查完成');
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">检查用户状态失败: ' + error.message + '</div>';
                console.error('检查用户状态失败:', error);
            }
        }
        
        // 检查所有用户订单
        async function checkAllOrders() {
            const resultDiv = document.getElementById('allOrders');
            try {
                console.log('开始检查所有用户订单...');
                
                // 尝试不同的用户名
                const possibleUsernames = ['Mike', 'mike', 'admin', 'testuser', 'testuser2'];
                const allOrders = {};
                
                for (const username of possibleUsernames) {
                    try {
                        const result = await fetch('http://localhost:8000/api/orders', {
                            headers: {
                                'Authorization': 'Bearer test-token-' + username.toLowerCase(),
                                'X-Username': username,
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        if (result.ok) {
                            const data = await result.json();
                            if (data.success && data.data.orders.length > 0) {
                                allOrders[username] = data.data.orders;
                                console.log(`找到用户 ${username} 的订单:`, data.data.orders.length, '个');
                            }
                        }
                    } catch (error) {
                        console.log(`用户 ${username} 无订单或请求失败`);
                    }
                }
                
                resultDiv.innerHTML = `
                    <div class="info">
                        <strong>所有用户订单检查结果:</strong><br>
                        <div class="json-display">${JSON.stringify(allOrders, null, 2)}</div>
                    </div>
                `;
                
                console.log('所有用户订单检查完成');
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">检查所有订单失败: ' + error.message + '</div>';
                console.error('检查所有订单失败:', error);
            }
        }
        
        // 模拟创建订单
        async function simulateCreateOrder() {
            const resultDiv = document.getElementById('createOrderResult');
            try {
                console.log('开始模拟创建订单...');
                
                const orderData = {
                    items: [
                        {
                            productId: 'F004',
                            product_name: '诊断测试商品',
                            price: 99.99,
                            quantity: 1
                        }
                    ],
                    shippingAddress: {
                        name: '诊断测试用户',
                        phone: '13800138000',
                        address: '诊断测试地址'
                    },
                    paymentMethod: 'alipay',
                    discount: 0
                };
                
                console.log('订单数据:', orderData);
                
                const result = await window.api.createOrder(orderData);
                console.log('创建订单结果:', result);
                
                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单创建成功</div>
                        <div class="info">订单号: ${result.data.order_number}</div>
                        <div class="json-display">${JSON.stringify(result.data, null, 2)}</div>
                    `;
                    
                    // 立即验证订单是否保存
                    setTimeout(async () => {
                        try {
                            const verifyResult = await window.api.getOrders();
                            if (verifyResult.success) {
                                const hasNewOrder = verifyResult.data.orders.some(order => 
                                    order.order_number === result.data.order_number
                                );
                                
                                if (hasNewOrder) {
                                    console.log('✓ 订单已正确保存');
                                } else {
                                    console.error('✗ 订单未保存到数据库');
                                }
                            }
                        } catch (error) {
                            console.error('验证订单保存失败:', error);
                        }
                    }, 1000);
                    
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 订单创建失败: ' + result.error + '</div>';
                    console.error('订单创建失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 创建订单错误: ' + error.message + '</div>';
                console.error('创建订单错误:', error);
            }
        }
        
        // 检查订单文件
        async function checkOrderFile() {
            const resultDiv = document.getElementById('orderFileResult');
            try {
                console.log('检查订单文件...');
                
                // 通过API获取订单数据
                const result = await window.api.getOrders();
                
                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单文件检查成功</div>
                        <div class="info">当前用户订单数量: ${result.data.orders.length}</div>
                        <div class="json-display">${JSON.stringify(result.data.orders, null, 2)}</div>
                    `;
                    console.log('订单文件检查完成，订单数量:', result.data.orders.length);
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 获取订单文件失败: ' + result.error + '</div>';
                    console.error('获取订单文件失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 检查订单文件错误: ' + error.message + '</div>';
                console.error('检查订单文件错误:', error);
            }
        }
        
        // 页面加载完成后运行
        window.addEventListener('load', () => {
            console.log('订单创建问题诊断工具加载完成');
            
            // 模拟用户登录
            const userData = {
                username: 'Mike',
                user_id: 'USER001',
                email: 'mike@example.com',
                phone: '1234567890',
                user_type: 'Customer',
                token: 'test-token-mike'
            };
            
            localStorage.setItem('currentUser', JSON.stringify(userData));
            localStorage.setItem('userData', JSON.stringify(userData));
            localStorage.setItem('authToken', userData.token);
            
            if (window.authManager) {
                window.authManager.currentUser = userData;
                window.authManager.isLoggedIn = true;
                window.authManager.userType = userData.user_type;
            }
            
            console.log('模拟用户登录完成:', userData);
        });
    </script>
</body>
</html>
